/*
 * @Author: 码上talk|RC
 * @Date: 2020-06-09 23:20:26
 * @LastEditTime: 2022-04-22 15:55:48
 * @LastEditors: 码上talk|RC
 * @Description:
 * @FilePath: /ma-distributor/mixins/common.js
 * @微信:  13680065830
 * @邮箱:  3189482282@qq.com
 * @oops: Just do what I think it is right
 */
import Vue from 'vue';
import { get, reject } from 'lodash'
import Toast from 'vant/toast/toast';
import Dialog from 'vant/dialog/dialog';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn'
import { mapState } from 'vuex'
import { appConfig } from '@/config/app'
import scanNavManager from '@/utils/scan-nav-manager'
import { v4 as uuidv4 } from 'uuid';
import * as uniApi from '@/utils/uni'
import currency  from 'currency.js';

dayjs.locale('zh-cn')
dayjs.extend(relativeTime);

Vue.mixin({
  filters: {
    addZero: (t) => {
      return t < 10 ? '0' + t : t + '';
    },
    amount (n) {
      if (!n) {
        return 0.00;
      }
      return n.toFixed(2);
    },
    prefixOssUrl (val) {
      return appConfig.staticUrl + val
    },
    numberFormat (v) {
      return v > 10000 ? ((v - v % 1000) / 10000 + 'W') : v
    },
    amountFormat (number, decimals = 2, thousands_sep = '', coin_symbol = '') {
      /*
      * 参数说明：
      * number：要格式化的数字
      * decimals：保留几位小数
      * thousands_sep：千分位符号
      * coin_symbol：货币符号
      * */

      return currency(number, { precision: decimals, separator: thousands_sep, symbol: coin_symbol }).format();
    },
    levelFilter (v) {
      if (v === 1) return '兑换会员'
      if (v === 2) return '普通会员'
      if (v === 3) return 'VIP会员'
      if (v === 4) return '银卡会员'
      if (v === 5) return '金卡会员'
      if (v === 10) return '代理'
      if (v === 11) return '至尊'
      if (v === 12) return '市场股东'
      return '默认'
    },
    purchanseTypeFilter (v) {
      if (v === 1) return '新订单';
      if (v === 2) return '预售';
      if (v === 3) return '预存';
      if (v === 5) return '自定义';
      if (v === 6) return '思雪新订单';
      if (v === 7) return '思雪预售';
    },
    purchanseStatusFilter (v) {
      if (v === -1) return '待支付'
      if (v === 0) return '已支付'
      if (v === 1) return '审核中'
      if (v === 3) return '待出库'
      if (v === 4) return '部分出库'
      if (v === 5) return '已出库'
    },
    relDayStr (s) {
      return s ? dayjs(s).toNow() : '--';
    }
  },
  data () {
    return {
      vtoast: Toast,
      vdialog: Dialog,
      scanNavManager,
      testVideoUrl: 'http://vfx.mtime.cn/Video/2019/02/04/mp4/190204084208765161.mp4'
    }
  },
  computed: {
    ...mapState(['isLogin']),
    ...mapState('user', ['info']),
    isDev () {
      return process.env.NODE_ENV == 'development'
    },
    MemberTypeName () {
      if (this.info.type === 1) return '兑换会员';
      if (this.info.type === 2) {
        if (this.info.levelId === 2) return '推广商-普通';
        if (this.info.levelId === 3) return '推广商-VIP';
        if (this.info.levelId === 4) return '推广商-银卡';
        if (this.info.levelId === 5) return '推广商-金卡';
      }
      if (this.info.type === 7) return '店主';
      if (this.info.type === 8) return '至尊会员';
      if (this.info.type === 9) return '市场股东';
    }
  },
  methods: {
    amountFormat (number, decimals = 2, thousands_sep = '', coin_symbol = '') {
      /*
      * 参数说明：
      * number：要格式化的数字
      * decimals：保留几位小数
      * thousands_sep：千分位符号
      * coin_symbol：货币符号
      * */

      return currency(number, { precision: decimals, separator: thousands_sep, symbol: coin_symbol }).format();
    },
    purchanseType (v) {
      if (v === 1) return '新订单';
      if (v === 2) return '预售';
      if (v === 3) return '预存';
      if (v === 5) return '自定义';
      if (v === 6) return '思雪新订单';
      if (v === 7) return '思雪预售';
    },
    revertFormStatus (v) {
      if (v == 0) return '未分拣'
      if (v == 1) return '保存'
      if (v == 2) return '审核中'
      if (v == 3) return '已通过'
      if (v == 4) return '未通过'
    },
    cancelStatus (v) {
      if (v === 1) return '待审批';
      if (v === 2) return '已通过';
      if (v === 3) return '未通过';
      if (v === 4) return '取消';
    },
    amountRetail (v) {
      const goodsItemsList = this.$_.get(v, 'goodsItemsList',[]) || [];
      if (goodsItemsList.length !== 0) {
        return this.isLogin ? this.$_.min(goodsItemsList.map(i => i.amountCost + i.amountCostAbove)) : this.$_.min(goodsItemsList.map(i => i.amount));
      } else {
        return this.isLogin ? this.$_.get(v, 'amountCost') : this.$_.get(v, 'amount');
      }
    },
    red: (url) => {
      uni.redirectTo({
        url: url,
        fail: (e) => {
          console.error(e);
        }
      });
    },
    nav (url, opts, config = {}) {
      if (config && config.isReuqireLogin) {
        if (!this.isLogin) {
          uni.showModal({
            title: '未登录',
            content: '前往登录',
            confirmText: '前往',
            success: (res) => {
              if (res.confirm) {
                this.nav(appConfig.loginUrl)
              } else if (res.cancel) { }
            }
          });
          return;
        }
      }
      uniApi.nav(url, opts)
    },
    lnav (url, {
      forceLogin = false
    } = {}) {
      if (this.isLogin) {
        this.nav(url)
      } else {
        if (forceLogin) {
          this.nav(appConfig.loginUrl)
        } else {
          uni.showModal({
            title: '未登录',
            content: '前往登录',
            confirmText: '前往',
            success: (res) => {
              if (res.confirm) {
                this.nav(appConfig.loginUrl)
              } else if (res.cancel) { }
            }
          })
        }
      }
    },
    back: () => {
      uni.navigateBack({
        delta: 1
      });
    },
    swi: (url) => {
      uni.switchTab({
        url: url
      });
    },
    setNavTitle (title) {
      uni.setNavigationBarTitle({
        title: title
      })
    },
    toast (s, d = 2000, i = 'none') {
      uni.showToast({
        title: s,
        duration: d,
        icon: i
      });
      setTimeout(() => {
        uni.hideToast()
      }, d + 500);
    },
    toastError (e, s = '服务器开小差了') {
      this.toast(s, 2000, 'error');
    },
    navToGoodsDetail (g) {
      const id = g.id;
      this.nav(`/subpackage/goods/pages/detail/index?id=${id}`);
    },
    get () {
      return get(...arguments)
    },
    log () {
      console.log(...arguments)
    },
    getDayjsObj (time) {
      return dayjs(time)
    },
    developing () {
      this.toast('开发中...')
    },
    setClipboardData (text, successText = '内容已复制') {
      if (text) {
        uni.setClipboardData({
          data: text,
          success: () => {
            this.toast(successText)
          }
        })
      }
    },
    makePhoneCall (mobile) {
      if (mobile) {
        uni.makePhoneCall({
          phoneNumber: mobile
        });
      }
    },
    getNodeInfo (id, inThis = true) {
      return new Promise(resolve => {
        let query
        if (inThis) {
          query = uni.createSelectorQuery().in(this);
        } else {
          query = uni.createSelectorQuery()
        }
        query.select(`#${id}`).boundingClientRect(data => {
          resolve(data)
        }).exec();
      })
    },
    saveBase64Img (base64) {
      let array = uni.base64ToArrayBuffer(base64.slice(22));
      let random = new Date().getTime();
      let filePath = wx.env.USER_DATA_PATH + `/${random}.png`;
      wx.getFileSystemManager().writeFile({
        filePath: filePath,
        data: array,
        encoding: 'binary',
        success: () => {
          this.saveImageToAlbum(filePath);
        },
        fail: err => { }
      })
    },
    saveImageToAlbum (img) {
      let fileName = new Date().getTime();
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.showModal({
              title: '提示',
              content: '需要获取相册权限',
              success: function (res) {
                if (res.confirm) {
                  wx.openSetting({
                    success (res) { }
                  })
                }
              }
            })
          }
        }
      })
      wx.downloadFile({
        url: 'https:' + img,
        filePath: wx.env.USER_DATA_PATH + "/" + fileName + ".png",
        success: (res) => {
          if (res.statusCode === 200) {
            wx.saveImageToPhotosAlbum({
              filePath: res.filePath,
              success: (res) => {
                this.toast('保存成功', 3000, 'success')
              }
            })
          }
        }
      })
    },
    prefixOssUrl (val) {
      return appConfig.staticUrl + val
    },
    black_Get (o, v, d = '--') {
      return this.$_.get(o, v) || d
    },
    isTraceCode (s) {
      let b = false;
      let t = '';
      if (s.indexOf('m.aoxqwl.com/trace/query?qrCode=') > -1) {
        b = true;
        t = s.split('?qrCode=')[1];
      }
      if (s.length === 8 && /^[A-Z][0-9]*/.test(s)) {
        b = true;
        t = s;
      }
      return { b, t };
    },
    isTraceCaptcha (s) {
      let b = false;
      let t = '';
      if (s.length <= 8 && /[0-9]*[A-Z]$/.test(s)) {
        b = true;
        t = s;
      }
      if (s.indexOf('m.aoxqwl.com/trace/query?captcha=') > -1) {
        b = true;
        t = s.split('?captcha=')[1];
      }
      return { b, t };
    },
    isTraceCodeV1 (s) {
      return s.indexOf('aoxueqio2o.com') > -1;
    },
    copyText (v) {
      uni.showModal({
        content: v,
        confirmText: '复制内容',
        success: (res) => {
          if (res.confirm) {
            uni.setClipboardData({
              data: v,
              success: () => {
                this.toast('复制成功')
              }
            });
          }
        }
      });
    },
    upload (authorize, file) {
      const { accessKey, host, policy, signature, callback } = authorize;
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: 'https://' + host,
          filePath: file.url,
          name: 'file',
          formData: {
            'name': file.url,
            'key': uuidv4(),
            'policy': policy,
            'OSSAccessKeyId': accessKey,
            'signature': signature,
            'success_action_status': '200',
            callback
          },
          success: (uploadFileRes) => {
            resolve(uploadFileRes)
          },
          fail: (e) => {
            console.log(e);
          }
        });
      }).then(res => {
        const jsonData = res.data
        const data = JSON.parse(jsonData)
        return data
      })
    },
    random (m) {
      return (Math.random() + m).toFixed(1)
    },
    getSystemInfo () {
      const res = uni.getSystemInfoSync();
      return [
        'iPhone X',
        'iPhone XR',
        'iPhone XS',
        'iPhone XS Max',
        'iPhone 11',
        'iPhone 11 Pro',
        'iPhone 11 Pro Max',
        'iPhone 12',
        'iPhone 12 Mini',
        'iPhone 12 Pro',
        'iPhone 12 Pro Max',
        'iPhone 13 Mini',
        'iPhone 13',
        'iPhone 13 Pro',
        'iPhone 13 Pro Max'].includes(res.model)
    },
    getServerExceptionMsg (s) {
      if (!s) {
        return '服务端错误~'
      } else {
        const mk = s.split('BizException: ')
        return mk.length === 2 ? mk[1] : '服务端错误~'
      }
    },
    getLeftTime (e, nt = dayjs()) {
      let l = 0;
      l = nt.diff(e);
      return {
        h: parseInt(l / (1000 * 60 * 60) % 24),
        m: parseInt(l / (1000 * 60) % 60),
        s: parseInt(l / 1000 % 60),
        _raw: l
      }
    },
    isNetEnvOk () {
      return new Promise((resolve, reject) => {
        uni.getNetworkType({
          success: (res) => {
            if (res.networkType !== 'wifi') {
              uni.showModal({
                content: '当前为非WIFI环境，是否使用流量观看直播',
                showCancel: true,
                confirmColor: '#db187c',
                success: function (res) {
                  if (res.confirm) {
                    resolve();
                  } else {
                    reject();
                  }
                }
              });
            } else {
              resolve();
            }
          }
        });
      });
    },
    navMa (appId, path, extraData) {
      wx.navigateToMiniProgram({
        appId,
        path,
        extraData,
        envVersion: appConfig.maEnv,
        success (res) {
        }
      })
    }
  }
});
